package udpEcho;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Server {
    private DatagramSocket  socket = null;//指定socket对象
    public Server(int port) throws SocketException {
        socket = new DatagramSocket(port);//对socket对象初始化，拿到端口号

    }
    //启动服务器
    public void start() throws IOException {
        //日志
        System.out.println("服务器启动");
        //处理请求
        while(true){
            //对接受的请求处理规整成receivePacket形式
            DatagramPacket receivePacket = new DatagramPacket(new byte[1024],1024);
            //接受已经被初始化过的请求
            socket.receive(receivePacket);
            //把接受的数据转成String类型的字符串，用于回显显示
            String request = new String(receivePacket.getData(),0,receivePacket.getLength());
            //处理请求并响应，这里使用echo（回显）
            String response = process(request);
            //把响应返回客户端，要使用DatagramPacket形式
            DatagramPacket requestPacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,receivePacket.getSocketAddress());
            // 把处理成DatagramPacket的响应发回
            socket.send(requestPacket);
            //打印日志
            System.out.printf("[%s:%d] req: %s,resp : %s\n",receivePacket.getAddress().toString(),
                    receivePacket.getPort(),request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        //指定服务器端口号，让客户端知道
        Server server = new Server(8080);
        server.start();
    }

    public String process(String request) {
        return request;
    }
}
